<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Exceptions\BusinessException;
use App\Helpers\CodeResponse;
use Illuminate\Support\Str;
use Modules\Admin\Services\PermissionService;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;

class AdminPermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 重置路由缓存
        // php artisan cache:forget spatie.permission.cache

        // 直接使用路由中配置的permission参数来判断 当前路由是否需要验证权限
        // 路由扩展了 aliasPermission aliasPermissions（资源型路由扩展方法） 方法 在方法中定义路由是否需要加入权限控制
        $need_permission = $request->route()->checkPermission();
        $admin = auth()->guard('admin')->user();
        // dd($admin->getALlPermissions()->toArray());
        if ($need_permission && !is_null($admin) && !$admin->super_admin) {
            // 权限检查【忽略超级管理员  超级管理员拥有所有权限】
            $permission_name = $request->route()->getPermissionName();
            try {
                if (!$admin->hasAllPermissions($permission_name)) {
                    throw new BusinessException(CodeResponse::PERMISSIONS_FAIL, '您没有当前操作权限！');
                }
            } catch (PermissionDoesNotExist $e) {
                if (Str::contains($e->getMessage(), 'There is no permission named')) {
                    // 当前路由配置为需要加入权限 但是还未更新到权限表中  这里自动添加进权限表
                    $routes = PermissionService::getInstance()->getRouteInformation($request->route());
                    PermissionService::getInstance()->savePermissions($routes, 'admin');
                    throw new BusinessException(CodeResponse::PERMISSIONS_FAIL, '您没有当前操作权限！');
                } else {
                    throw new BusinessException(CodeResponse::PERMISSIONS_FAIL, $e->getMessage());
                }
            }
        }

        return $next($request);
    }
}
